package com.one.blocks.rbac.manager;

import com.alicp.jetcache.anno.CacheInvalidate;
import com.alicp.jetcache.anno.CacheType;
import com.alicp.jetcache.anno.Cached;
import com.one.blocks.mvc.manager.AbstractBatchManager;
import com.one.blocks.rbac.constant.RbacConstant.UserCache;
import com.one.blocks.rbac.domain.SysAccount;
import com.one.blocks.rbac.domain.SysUser;
import com.one.blocks.rbac.domain.SysUserAccount;
import com.one.blocks.rbac.domain.SysUserRole;
import com.one.blocks.rbac.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.List;

/**
 * @author <a href="mailto:idler41@163.con">idler41</a> created on 2022-05-01 10:06:14
 */
@Service
public class SysUserManager extends AbstractBatchManager<SysUserMapper, SysUser> {

    @Autowired
    private SysAccountManager sysAccountManager;

    @Autowired
    private SysUserRoleManager sysUserRoleManager;

    @Autowired
    private SysUserAccountManager sysUserAccountManager;

    @Autowired
    public SysUserManager(SysUserMapper mapper) {
        super(mapper);
    }

    public SysUser getByAccountId(Integer accountId) {
        return mapper.getByAccountId(accountId);
    }

    @CacheInvalidate(area = UserCache.AREA, name = UserCache.ID, key = "#id")
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean delete(Serializable id) {
        return super.delete(id);
    }

    @CacheInvalidate(area = UserCache.AREA, name = UserCache.ID, key = "#id")
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateById(SysUser entity) {
        return super.updateById(entity);
    }

    @CacheInvalidate(area = UserCache.AREA, name = UserCache.ID, key = "#id")
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateSelectiveById(SysUser entity) {
        return super.updateSelectiveById(entity);
    }

    @Cached(area = UserCache.AREA, name = UserCache.ID, key = "#id", cacheType = CacheType.BOTH)
    @Override
    public SysUser get(Serializable id) {
        return super.get(id);
    }

    @Transactional(rollbackFor = Exception.class)
    public void insert(
            SysUser sysUser, List<SysUserRole> sysUserRole,
            SysAccount sysAccount, SysUserAccount sysUserAccount
    ) {
        mapper.insert(sysUser);
        sysAccountManager.insert(sysAccount);

        sysUserAccount.setUserId(sysUser.getId());
        sysUserAccount.setAccountId(sysAccount.getId());
        sysUserAccountManager.insert(sysUserAccount);

        for (SysUserRole userRole : sysUserRole) {
            userRole.setUserId(sysUser.getId());
            sysUserRoleManager.insert(userRole);
        }
    }
}